package com.javaDemo.ti;

import java.util.Stack;

/**
 * @ClassName: Zuidaolujinghe
 * @Auther: csy
 * @Date: 2021/7/1 20:31
 * @Description:
 */

public class Zuidaolujinghe {

      public static class TreeNode {
          int val;
          TreeNode left;
          TreeNode right;
          TreeNode() {}
          TreeNode(int val) { this.val = val; }
          TreeNode(int val, TreeNode left, TreeNode right) {
              this.val = val;
              this.left = left;
              this.right = right;
          }
      }
    static Stack<Integer> results = new Stack<>();
    static int sum = 0;

    public static void main(String[] args) {
        TreeNode treeNode=new TreeNode(-10);
        treeNode.left=new TreeNode(9);
        treeNode.right=new TreeNode(20);
        treeNode.right.left=new TreeNode(15);
        treeNode.right.right=new TreeNode(-1);
        putList(treeNode);
        System.out.println(results);
    }

    private static void putList(TreeNode treeNode) {
        if(treeNode!=null){
            if (treeNode.left!=null){
                putList(treeNode.left);
            }
            if(sum+treeNode.val>sum){
                sum+=treeNode.val;
            }else{
                sum=0;
            }
            results.add(treeNode.val);
            if(treeNode.right!=null){
                putList(treeNode.right);
            }
        }

    }
    int maxSum=0;
    public int maxGain(TreeNode node) {
        if (node == null) {
            return 0;
        }

        // 递归计算左右子节点的最大贡献值
        // 只有在最大贡献值大于 0 时，才会选取对应子节点
        int leftGain = Math.max(maxGain(node.left), 0);
        int rightGain = Math.max(maxGain(node.right), 0);

        // 节点的最大路径和取决于该节点的值与该节点的左右子节点的最大贡献值
        int priceNewpath = node.val + leftGain + rightGain;

        // 更新答案
        maxSum = Math.max(maxSum, priceNewpath);

        // 返回节点的最大贡献值
        return node.val + Math.max(leftGain, rightGain);
    }
}
